import { verifyToken } from '@/utils/backend/auth'
import { HttpStatus } from '@/utils/httpStatus'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

// 白名单路径
const whiteList = ['/api/auth/code', '/api/auth/login']

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl
  console.log('pathname:', pathname)

  // 白名单直接放行
  if (whiteList.includes(pathname)) {
    console.log('白名单路径', pathname)

    return NextResponse.next()
  }
  console.log('走到这里代表没放行')

  // 从请求头获取 Authorization token
  const authHeader = request.headers.get('Authorization')
  const token = authHeader?.replace('Bearer ', '') // 移除 Bearer 前缀

  if (!token) {
    // API 请求返回 401
    if (pathname.startsWith('/api')) {
      return NextResponse.json(
        {
          success: false,
          error: 'unauthorized',
          message: '请先登录'
        },
        { status: HttpStatus.UNAUTHORIZED }
      )
    }
    // 页面请求重定向到登录
    // return NextResponse.redirect(new URL('/login', request.url))
  }

  // 验证 token
  const tokenResult = await verifyToken(token!)
  if (!tokenResult.valid) {
    if (pathname.startsWith('/api')) {
      return NextResponse.json(
        {
          success: false,
          error: tokenResult.error,
          message: tokenResult.message
        },
        { status: HttpStatus.UNAUTHORIZED }
      )
    }
    // return NextResponse.redirect(new URL('/login', request.url))
  }

  return NextResponse.next()
}

// 配置需要进行中间件处理的路由
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/api/:path*'
  ]
}
